package com.tqz.juc.aqs;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>使用 `CountDownLatch` 模拟并发
 *
 * @author tianqingzhao
 * @since 2022/2/5 18:32
 */
public class CountDownLatchTest4 {
    
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CountDownLatch cdl = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            CountRunnable runnable = new CountRunnable(cdl);
            executorService.execute(runnable);
        }
    }
    
    static class CountRunnable extends Thread {
        
        private CountDownLatch countDownLatch;
        
        public CountRunnable(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }
        
        @Override
        public void run() {
            try {
                synchronized (countDownLatch) {
                    // 每次减少一个容量
                    countDownLatch.countDown();
                    System.out.println("thread counts = " + (countDownLatch.getCount()));
                }
                countDownLatch.await();
                System.out.println("concurrency counts = " + (100 - countDownLatch.getCount()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}



